//
//  ATScriptStepEditorView.m
//  AutomationTool
//
//  Created by Laurie Marmon on 3/3/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ATScriptStepEditorView.h"
#import "ATScriptStep.h"
#import "ATScriptStepParameter.h"
#import "ATScriptStepTemplate.h"

#pragma mark Private Properties

@interface ATScriptStepEditorView ()

@property (nonatomic, strong) NSTextField *defaultText;
@property (nonatomic, strong) NSMutableArray *dynamicSubviews;

@end

#pragma mark Main Class Implementation

@implementation ATScriptStepEditorView

@synthesize defaultText = _defaultText;
@synthesize dynamicSubviews = _dynamicSubviews;
@synthesize delegate = _delegate;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.defaultText = [[NSTextField alloc] initWithFrame:CGRectMake(10,10,600,40)];
        [self.defaultText setStringValue:@"Select a script step to get started."];
        [self.defaultText setBackgroundColor:[NSColor clearColor]];
        [self.defaultText setBordered:NO];
        [self.defaultText setEditable:NO];
        [self addSubview:self.defaultText];
        self.dynamicSubviews = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (BOOL)isFlipped
{
    return YES;
}

- (void)resetDefaultView
{
    [self.defaultText setHidden:NO];
    
    for (NSView *view in self.dynamicSubviews) {
        [view removeFromSuperview];
    }
    
    [self.dynamicSubviews removeAllObjects];
}

- (void)drawViewForScriptStep:(ATScriptStep *)scriptStep
{
    if (scriptStep != nil) {
        [self.defaultText setStringValue:[NSString stringWithFormat:@"%@ :\n    %@", scriptStep.name, scriptStep.userDescription]];
        [self.defaultText setFont:[NSFont boldSystemFontOfSize:0]];
    } else {
        [self.defaultText setStringValue:@"Select a script step to get started."];
    }
    
    for (NSView *view in self.dynamicSubviews) {
        [view removeFromSuperview];
    }
    
    [self.dynamicSubviews removeAllObjects];
    
    ATScriptStepTemplate *template = scriptStep.stepTemplate;
    for (int index = 0; index < [template.parameters count]; index++) {
        ATScriptStepParameter *parameter = (ATScriptStepParameter *)[template.parameters objectAtIndex:index];
        if ([parameter.possibleValues count] == 0) {
            [self addTextFieldForParameter:parameter asParameterNumber:index withValue:[scriptStep valueForParameterName:parameter.name]];
        } else {
            [self addPopUpButtonForParameter:parameter withValues:parameter.possibleValues asParameterNumber:index withValue:[scriptStep valueForParameterName:parameter.name]];
        }
    }
}

- (void)addTextFieldForParameter:(ATScriptStepParameter *)parameter asParameterNumber:(int)parameterNumber withValue:(id)value
{
    int verticalOffset = 60;
    int horizontalOffset = 20;
    int fieldHeight = 25;
    int labelWidth = 150;
    int horizontalSpacingOffset = 10;
    int verticalSpacingOffset = 10;
    int horizontalFieldOffset = horizontalOffset + labelWidth + horizontalSpacingOffset;
    int verticalFieldOffset = fieldHeight + verticalSpacingOffset;
    int fieldWidth = 400;
    
    NSTextField *defaultFieldLabel = [[NSTextField alloc] 
                                     initWithFrame:CGRectMake(horizontalOffset,
                                                                   verticalOffset + (verticalFieldOffset*parameterNumber),
                                                                   labelWidth,
                                                                   fieldHeight)];
    NSTextField *defaultTextField = [[NSTextField alloc] 
                                     initWithFrame:CGRectMake(horizontalFieldOffset,
                                                              verticalOffset + (verticalFieldOffset*parameterNumber),
                                                              fieldWidth,
                                                              fieldHeight)];
    //set attributes for the text label
    [defaultFieldLabel setStringValue:parameter.name];
    [defaultFieldLabel setBackgroundColor:[NSColor clearColor]];
    [defaultFieldLabel setBordered:NO];
    [defaultFieldLabel setAlignment:NSRightTextAlignment];
    [defaultFieldLabel setToolTip:parameter.userDescription];
    [defaultFieldLabel setEditable:NO];
    
    //set attributes for the text field
    [defaultTextField setDelegate:self];
    [defaultTextField setIdentifier:parameter.name];
    [defaultTextField setToolTip:parameter.userDescription];
    if (value) {
        [defaultTextField setObjectValue:value];
    } else {
        if ([parameter.name rangeOfString:@"Element Name"].location != NSNotFound) {
            [defaultTextField.cell setPlaceholderString:@"Use the Accessibility Inspector to find UI element names/labels."];
        } else if ([parameter.name rangeOfString:@"Message"].location != NSNotFound ||
                   [parameter.name isEqualToString:@"Typed String"]) {
            [defaultTextField.cell setPlaceholderString:@"Enter a string value, enclosed in quotes (\"\")."];
        } else if ([parameter.name rangeOfString:@"Variable"].location != NSNotFound) {
            [defaultTextField.cell setPlaceholderString:@"Enter a variable name to save the script step result."];
        } else if ([parameter.name rangeOfString:@"Value"].location != NSNotFound ||
                   [parameter.name rangeOfString:@"Name"].location != NSNotFound) {
            [defaultTextField.cell setPlaceholderString:@"Enter a string, with quotes (\"\"), or a variable name."];            
        } else {
            //nothing else to set
        }
    }
    
    [self addSubview:defaultFieldLabel];
    [self addSubview:defaultTextField];
    
    [self.dynamicSubviews addObject:defaultFieldLabel];
    [self.dynamicSubviews addObject:defaultTextField];
}

- (void)addPopUpButtonForParameter:(ATScriptStepParameter *)parameter withValues:(NSArray *)values asParameterNumber:(int)parameterNumber withValue:(id)value
{
    int verticalOffset = 60;
    int horizontalOffset = 20;
    int fieldHeight = 25;
    int labelWidth = 150;
    int horizontalSpacingOffset = 10;
    int verticalSpacingOffset = 10;
    int horizontalFieldOffset = horizontalOffset + labelWidth + horizontalSpacingOffset;
    int verticalFieldOffset = fieldHeight + verticalSpacingOffset;
    int fieldWidth = 400;

    NSTextField *defaultFieldLabel = [[NSTextField alloc] 
                            initWithFrame:CGRectMake(horizontalOffset,
                                                     verticalOffset + (verticalFieldOffset*parameterNumber),
                                                     labelWidth,
                                                     fieldHeight)];

        
    NSPopUpButton *defaultPopUpButton = [[NSPopUpButton alloc] 
                              initWithFrame:CGRectMake(horizontalFieldOffset,
                                                     verticalOffset + (verticalFieldOffset*parameterNumber),
                                                     fieldWidth,
                                                     fieldHeight)
                              pullsDown:NO];
    
    //set attributes for the text label
    [defaultFieldLabel setStringValue:parameter.name];
    [defaultFieldLabel setBackgroundColor:[NSColor clearColor]];
    [defaultFieldLabel setBordered:NO];
    [defaultFieldLabel setAlignment:NSRightTextAlignment];
    [defaultFieldLabel setToolTip:parameter.userDescription];
    [defaultFieldLabel setEditable:NO];
    
    //set attributes for the popup button
    [defaultPopUpButton addItemsWithTitles:values];
    [defaultPopUpButton setIdentifier:parameter.name];
    [defaultFieldLabel setToolTip:parameter.userDescription];
    [defaultPopUpButton setTarget:self];
    [defaultPopUpButton setAction:@selector(popUpDidChange:)];
    if (value) {
        [defaultPopUpButton selectItemWithTitle:value];
        [self popUpDidChange:defaultPopUpButton];
    }
    
    [self addSubview:defaultFieldLabel];
    [self addSubview:defaultPopUpButton];
    
    [self.dynamicSubviews addObject:defaultFieldLabel];
    [self.dynamicSubviews addObject:defaultPopUpButton];
}

#pragma mark Delegate Implementation

- (void)controlTextDidEndEditing:(NSNotification *)aNotification
{
    NSString *value = [[aNotification object] stringValue];
    NSString *paramName = [[aNotification object] identifier];
    
    [self.delegate editorView:self didChangeParameterName:paramName toValue:value];
}

- (void)popUpDidChange:(id)sender
{
    NSString *value = [sender titleOfSelectedItem];
    NSString *paramName = [sender identifier];
    
    [self.delegate editorView:self didChangeParameterName:paramName toValue:value];
}

@end
